<template>
    <div id="app" class="complaint">
        <scroll-fixed>
            <page-bar>
                <a @click="cancel" slot="left">取消</a>
                <a href="javascript:;" class="submit" slot="right" :class="{'disabled': !formStatus || posting}" @click="submit">发送</a>
            </page-bar>
        </scroll-fixed>
        <div class="edit-box">
            <textarea class="editor" v-model.trim="form.content"  @input="wordCut" placeholder="请写下您的看法吧"></textarea>
            <div class="uploader-list">
                <div class="item" v-for="(img,index) in form.imgs" :key="index"  @click="previewImage(index)" :style="{'background-image':'url('+img+')'}">
                    <a href="javascript:void(0);" class="close" @click.self.stop="removeImage(index)"></a>
                </div>
            </div>
            <div class="tool-bar">
                <div class="tools">
                    <span id="filePicker">
                        <i class="uicon uicon-photo"></i>
                    </span>
                </div>

                <!-- <span class="count"><label>{{form.content.length}}</label>/{{max}}</span> -->
            </div>
        </div>

        <ui-preview :config="preview" v-if="preview.status" @close="preview.status = false" @remove="removeImage" />
    </div>
</template>

<script>
import scrollFixed from "@/components/scrollFixed.vue";
import pageBar from "@/components/pagebar.vue";
import uiPreview from "@/components/preview.vue";

//获取选中的文本
function getSelectText(editor) {
    if (!editor) return;
    editor.focus();
    if (editor.document && editor.document.selection)
        return editor.document.selection.createRange().text;
    else if ("selectionStart" in editor)
        return editor.value.substring(
            editor.selectionStart,
            editor.selectionEnd
        );
}

export default {
    name: "square-create",
    components: {
        [pageBar.name]: pageBar,
        [scrollFixed.name]: scrollFixed,
        [uiPreview.name]: uiPreview
    },
    data() {
        return {
            posting: false,
            max: 200,
            isDone: false,
            preview: {
                status: false,
                active: 0,
                list: []
            },
            form: {
                content: "",
                filenames: [],
                imgs: []
            }
        };
    },
    computed: {
        formStatus() {
            return (
                this.form.content.length > 0 && this.form.content.length <= 200
            );
        }
    },
    mounted() {
        // 修改头像
        window.upload = WebUploader.create({
            // 选完文件后，是否自动上传。
            auto: true,
            // 文件接收服务端。
            server: this.$config.api + "?ct=upload&ac=index",
            pick: "#filePicker",
            // 只允许选择图片文件。
            accept: {
                capture: "",
                title: "Images",
                extensions: "gif,jpg,jpeg,bmp,png",
                mimeTypes: "image/*"
            },
            chunked: true,
            chunkSize: 1 * 1024 * 1024,
            formData: {
                file: "file",
                _token: localStorage.getItem("token")
            }
        });

        upload.on("beforeFileQueued", file => {
            file.guid = WebUploader.Base.guid();
        });

        upload.on("uploadBeforeSend", (object, data, headers) => {
            headers["X-Requested-With"] = "XMLHttpRequest";
            data.guid = object.file.guid;
        });

        // 上传成功
        upload.on("uploadSuccess", (file, response) => {
            var res = JSON.parse(response._raw);
            this.form.filenames.push(res.data.filename);
        });

        function removeInputCapture() {
            let pick = document.querySelector("#filePicker input[type=file]");
            if (!pick) {
                setTimeout(() => {
                    removeInputCapture();
                }, 300);
                return false;
            }

            pick.removeAttribute("capture");
        }
        removeInputCapture();
        // 当有文件被添加进队列的时候
        upload.on("fileQueued", file => {
            upload.makeThumb(
                file,
                (error, src) => {
                    if (error) {
                        this.$toast(error);
                    } else {
                        this.form.imgs.push(src);
                    }
                },
                1,
                1
            );
        });
    },
    methods: {
        cancel(){
            if(!document.referrer){
                this.$router.replace({name:'home'});
            }else{
                this.$router.back();
            }
        },
        previewImage(idx) {
            this.preview.active = idx;
            this.preview.list = this.form.imgs.concat();
            this.preview.status = true;
        },
        wordCut(e) {
            var len = e.target.value.length - getSelectText(e.target).length;
            var num = this.max;
            if (len > num && e.keyCode !== 8) {
                e.preventDefault();
                e.stopPropagation();
                e.target.value = e.target.value.substr(0, num);
                this.form.content = e.target.value;
                return false;
            }
        },
        submit() {
            if (!this.formStatus || this.posting) return false;
            this.postDate();
        },
        postDate() {
            this.posting = true;
            this.$http
                .post("?ct=member_publish&ac=add_publish", {
                    image: this.form.filenames.join(','),
                    content: this.form.content
                })
                .then(response => {
                    let { data } = response;
                    if (data.code == 0) {
                        this.form.imgs = [];
                        this.form.filenames = [];
                        this.form.content = [];
                        this.$toast("发布成功");
                        // this.$router.replace('/');
                        this.$router.replace({
                            name:'detail',
                            query:{
                                id:data.data.id
                            },
                            params:{
                                init_data:data.data
                            }
                        })
                    } else {
                        this.$toast(data.msg);
                    }
                })
                .catch(e => {
                    window.$zEvent.$emit("ERROR", e);
                    this.$toast(e);
                })
                .finally(() => {
                    this.posting = false;
                });
        },
        removeImage(idx) {
            this.form.imgs.splice(idx, 1);
            this.form.filenames.splice(idx, 1);
            //清除webuploader队列
            upload.removeFile(upload.getFiles()[idx], true);
        }
    }
};
</script>

<style lang="less">
.complaint {
    .page-title {
        color: #282828;
        font-size: 36px;
    }
    .edit-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-direction: column;
        height: 481px;
        margin-top: 20px;
        background-color: #fff;
        .editor {
            flex: 1;
            padding: 30px;
            width: 100%;
            font-size: 34px;
            color: #282828;
            line-height: 52px;
            outline: none;
            border: none;
            &::-webkit-input-placeholder {
                font-size: 28px;
                color: #c6c6c6;
            }
        }
        .uploader-list {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
            .item {
                flex-grow: 0;
                flex-shrink: 0;
                background-color: #f5f5f5;
                position: relative;
                margin-left: 20px;
                width: 150px;
                height: 150px;
                border-radius: 10px;
                background-repeat: no-repeat;
                background-position: top center;

                .close {
                    position: absolute;
                    top: -6px;
                    right: -6px;
                    width: 28px;
                    height: 28px;
                    border-radius: 50%;
                    background-color: #e64a19;

                    &::after,
                    &::before {
                        content: "";
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        transform: translate(-50%, -50%) rotate(45deg);
                        background-color: #fff;
                        border-radius: 10px;
                    }

                    &:before {
                        width: 14px;
                        height: 2px;
                    }

                    &::after {
                        width: 2px;
                        height: 14px;
                    }
                }
            }
        }

        .tool-bar {
            width: 100%;
            padding: 30px;
            display: flex;
            justify-content: space-between;
            align-items: cetner;
            font-size: 24px;
            color: #c6c6c6;

            label {
                color: #282828;
            }
        }
    }
    .submit{
        &.disabled {
            opacity: 0.6;
        }
    }

    #filePicker {
        overflow: hidden;
        input {
            opacity: 0;
        }
    }
    .report-done {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 158px 30px 30px;

        .tit {
            margin-top: 66px;
            margin-bottom: 30px;
            font-size: 36px;
            color: #282828;
        }
        p {
            margin-bottom: 20px;
            line-height: 1;
            font-size: 32px;
            color: #666;

            a {
                color: #e64a19;
            }
        }
        .done {
            margin-top: 70px;
            width: 100%;
        }
    }
}
</style>

